package com.aiyun.securiy.login.security.custom;

import java.io.IOException;
import java.security.Key;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aiyun.securiy.login.security.UserList;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


	private static final int expiration = 3600;

	static byte[] keyBytes = Decoders.BASE64.decode("dW5iNXNaRTNNaFoya3doVk1VNmVDaHNaQUVITkhjU2pLV2U4RlJBWDllaEhkdVdHZHJjWlFhVlhZSjgzSFE1NWZ6d0R0VVBKeTJEUWZVZmNVMkhZcnNtckNaVkFwdDNXNDhXUGp1QVF2Y2N5c3pIdkFiZVdlUmZYZFVYOVczNXQ=");
	private static final Key secretKey =  Keys.hmacShaKeyFor(keyBytes);

	private final UserList userList;

	public LoginSuccessHandler(UserList userList) {
		this.userList = userList;
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//		Date now = new Date();
//		Date expireDate = new Date(now.getTime() + expiration * 1000L);
//		String compact = Jwts
//				.builder()
//				.signWith(secretKey, SignatureAlgorithm.HS256)
//				.setIssuedAt(now)
//				.setNotBefore(now)
//				.setExpiration(expireDate)
//				.setSubject(username)
//				.claim("roles", authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
//				.compact();
		String token = UUID.randomUUID().toString();
		userList.setToken(token, authentication);
		httpServletResponse.setHeader("Authorization", token);
		httpServletResponse.getWriter().write("{\"result\":\"" + token + "\"}");
	}
}
